package com.briup.smartcity.service.impl;

import com.briup.smartcity.bean.BaseUser;
import com.briup.smartcity.exception.ServiceException;
import com.briup.smartcity.mapper.BaseUserMapper;
import com.briup.smartcity.mapper.extend.BaseLogExtendMapper;
import com.briup.smartcity.mapper.extend.BaseUserExtendMapper;
import com.briup.smartcity.mapper.extend.Userlstoken;
import com.briup.smartcity.service.IBaseUserService;
import com.briup.smartcity.utils.JwtUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


/*
service层实现类
 */
@Service
public class BaseUserServiceImpl implements IBaseUserService {
    @Autowired
    private BaseUserExtendMapper extendmapper;
    @Autowired
    private BaseUserMapper mapper;
    @Autowired
    private Userlstoken map1;
    @Autowired
    private BaseLogExtendMapper map2;
    @Override
    public String login(String username, String password) throws ServiceException {
        //使用username信息查找对应的数据库中的用户信息
        BaseUser user = extendmapper.selectBaseUserByUsername(username);
        if(user == null){
            throw new ServiceException("用户名不存在");
        }

        if(!user.getPassword().equals(password)){
            //密码错误
            throw new ServiceException("密码错误");
        }
        if(map1.selectuserToken(username)==1){
            long nd = 1000*24*60*60;
            long nh = 1000*60*60;
            long nm = 1000*60;
            long date = new Date().getTime();
//            System.out.println(map2.findNewLog());
//            System.out.println(map2.findNewLog().getLogTime());
            Date date1 = map2.findNewLog().getLogTime();
            long  min = (date-date1.getTime())%nd%nh/nm;
            //System.out.println(min);
            if(min<=1){
                throw new ServiceException("此账号已在其他地方登录");
            }
        }
        //创建map对象，用来生成token字符串的复合信息
        HashMap<String, Object> userInfo = new HashMap<>();
        userInfo.put("role",user.getRole());
        userInfo.put("Id",user.getUserId());
        userInfo.put("realName",user.getRealname());
        map1.updateToken(username,1);
        return  JwtUtil.sign(username,userInfo);

    }

    @Override
    public void loginout() throws ServiceException {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = sra.getRequest();
        String token = request.getHeader("Authorization");
        //extendmapper.updateloginoutstatus(JwtUtil.getUserId(token));
//        map1.updateToken(JwtUtil.getUserId(token),"11111");
        map1.updateToken(JwtUtil.getUserId(token),0);
    }

    @Override
    public BaseUser currentUserInfo(String token) throws ServiceException {
        String username = JwtUtil.getUserId(token);
        //2.调用mapper查询根据username获取用户的所有信息
        return extendmapper.selectBaseUserByUsername(username);
    }

    @Override
    public PageInfo<BaseUser> pageQuery(int pageNum, int pageSize, String username, Integer role) throws ServiceException {
        PageHelper.startPage(pageNum,pageSize,true);
        List<BaseUser> list = extendmapper.getInfoByUsername(username);
        return new PageInfo<>(list);
    }

    //    更新用户
    @Override
    public void updateUser(BaseUser baseUser,String token) throws ServiceException {
        Integer userId2 = baseUser.getUserId();
        Integer role2 = baseUser.getRole();
        BaseUser user2 = mapper.selectByPrimaryKey(userId2);
        if (user2==null){
            throw new ServiceException("用户不存在");
        }
        String username2 = JwtUtil.getUserId(token);
        BaseUser baseUser2 = extendmapper.getRoleByUsername(username2);
        Integer role = baseUser2.getRole();
        if (role==1&&role2==0){
            throw new ServiceException("该用户权限较低，不能修该权限的用户");
        }
        mapper.updateByPrimaryKeySelective(baseUser);
    }

    //    更新用户头像
    @Override
    public void updateUserIcon(int id, String alterUserIcon) throws ServiceException {
        System.out.println(alterUserIcon);
        BaseUser user = mapper.selectByPrimaryKey(id);
        System.out.println("user" + user.getStatus());
        Integer statu = user.getStatus();
        if (statu==1){
            throw new ServiceException("该用户处于禁用状态，不能修改头像");
        }

        extendmapper.updateIconById(id,alterUserIcon);
    }

    @Override
    public void deleteUserById(Integer id) throws ServiceException {
        BaseUser user3 = mapper.selectByPrimaryKey(id);

        Integer role = user3.getRole();
        //管理员权限较高，不能删除
        if (role==0){
            throw new ServiceException("该用户是管理员，权限较高，不能删除，若要删除请就降低权限");
        }
        mapper.deleteByPrimaryKey(id);
    }

    //通过id删除用户信息

    //  分页模糊查询
    @Override
    public PageInfo<BaseUser> pageQuery2(int pageNum, int pageSize, String username, Integer role,String token) throws ServiceException {
        String username2 = JwtUtil.getUserId(token);
        BaseUser baseUser2 = extendmapper.getRoleByUsername(username2);
        Integer statu2 = baseUser2.getStatus();
        if (statu2==1){
            throw new ServiceException("该用户处于禁止状态");
        }
        PageHelper.startPage(pageNum,pageSize,true);
        List<BaseUser> list2 = extendmapper.getInfoByUsernameAndRole(username, role);
        return  new PageInfo<>(list2);
    }

    @Override
    public void updateStatus(String username) throws ServiceException {
        extendmapper.updateUserStatus(username);
    }
}
